// Generated on 2016-03-17 using generator-angular 0.15.1
'use strict';

var gulp = require("gulp");
var $ = require('gulp-load-plugins')();
var concat = require('gulp-concat');
var rimraf = require("rimraf");
var jasmine = require('gulp-jasmine');
var htmlmin = require('gulp-htmlmin');
var wiredep = require('wiredep').stream;
var openURL = require('open');
var imagemin = require('gulp-imagemin');
var gulpSequence = require('gulp-sequence');
var runSequence = require('run-sequence');
//压缩js
var minify      = require('gulp-minify');
//错误处理插件plumber
var plumber     = require('gulp-plumber');
var uglify = require('gulp-uglify');
var moment = require('moment');
var rename = require("gulp-rename");

var yeoman = {
    app: require('./bower.json').appPath || 'src',
    dist: 'dist'
};

var paths = {
    tpl:'src/tpl/*',
    scripts:{
        service:'dist/src/services/*.js',
        controller:'dist/src/controllers/**/*.js',
        allJS:'src/**/*.js',
        watchAllJs:['src/**/**/*.js'],
        serviceMin:'dist/src/service/service.min.js',
        directiveMin:'dist/src/directives/directive.min.js',
        mainMin:'dist/src/main.min.js',
        residue:[
                // 'dist/src/config.js',
                'dist/src/directives/ui-nav.js',
                'dist/src/directives/ng-thumb.js',
                'dist/src/directives/ui-shift.js'
            ]
    },
    styles: [yeoman.app + '/css/**/*.css'],
    karma: 'test/karma.conf.js',
    karma_dnx: 'test/karma.conf.dnx.js',
    views: {
        main: yeoman.app + '/index.html',
        files: [yeoman.app + '/tpl/**/*.html'],
    },
    css:'src/css/*.css',
    html:'src/**/*.html',
    index:'src/test.html',
    dirname:'dist',
};
    

///////////
// Tasks //
///////////

//test
gulp.task('testHtmlmin',function () {
    var options = {
        removeComments: true,  //清除HTML注释
        collapseWhitespace: true,  //压缩HTML
        collapseBooleanAttributes: true,  //省略布尔属性的值 <input checked="true"/> ==> <input checked />
        removeEmptyAttributes: true,  //删除所有空格作属性值 <input id="" /> ==> <input />
        removeScriptTypeAttributes: true,  //删除<script>的type="text/javascript"
        removeStyleLinkTypeAttributes: true,  //删除<style>和<link>的type="text/css"
        minifyJS: true,  //压缩页面JS
        minifyCSS: true  //压缩页面CSS
    };
   return gulp.src(paths.index)
        .pipe(htmlmin(options))
        .pipe(gulp.dest('dist'))
        .pipe($.plumber())
        .pipe($.connect.reload());
});

//无用
gulp.task('useref',function(){
    return gulp.src('src/index.html')
        .pipe($.useref())
        .pipe(gulp.dest('build'));
})
//无用end

//清除dist/src下文件
gulp.task("clean",function(cb){
    rimraf('dist/src',cb);
});
gulp.task("clean:rev",function(cb){
    rimraf('dist/rev',cb);
});
gulp.task("clean:componentRev",function(cb){
    rimraf('dist/componentRev',cb);
});
gulp.task("clean:index",function(cb){
    rimraf('dist/*.html',cb);
});

gulp.task("clean:dist",function(cb){
    return gulp.src(['dist/*','!dist/libs'], { read: false }) // much faster 
    .pipe($.clean());
})

//在dist文件目录下（build完全后）运行项目
gulp.task('start:server', function () {
    $.connect.server({
        root: ['dist',__dirname],//?
        port: 80,
        livereload: true,
        fallback: 'dist/index.html'
    });
});
//在src文件目录下运行项目（日常使用）
gulp.task('start:serverSrc', function () {
    $.connect.server({
        root: ['src',__dirname],//?
        port: 80,
        livereload: true,
        fallback: 'src/index.html',
    });
});
//watch
gulp.task('watch',function(){
    // $.watch(paths.scripts.watchAllJs,function(e){
    //     babelFile(e.path);
    // })
    $.watch([paths.html,'!src/index.html'])
    .pipe($.changed('../src',{extension:'.html'}))//?
    .pipe($.plumber())
    .pipe($.connect.reload());

    $.watch(paths.index,function(){
         gulp.start('testHtmlmin');
    })

    $.watch(paths.css)
    .pipe($.plumber())
    .pipe($.connect.reload());

});

// function babelFile(file){
//   var fileurls = file.replace(/[^\\]*$/,"").replace(/src/,"dist/src").replace(/\//g,"\\");
   
//   gulp.src([file])
//     .pipe($.typescript(tsProject))
//     .pipe($.babel({
//       presets: ['es2015']
//     }))
//     .pipe(gulp.dest(fileurls))
//     .pipe($.debug({title: "编译"}))
//     .pipe($.plumber())
//     .pipe($.connect.reload());
// }

gulp.task('start:dev', ['watch','start:server'], function () {
    //openURL('http://127.0.0.1:5000');
     openURL('http://localhost:5001')
});

gulp.task('start',['clean:dist','testHtmlmin'],function(){
    gulp.start("start:dev");
})
//移动config.js config.lazyload.js(现在用不到)
gulp.task('jsMove',function(){
     return gulp.src(['src/config.js','src/config.lazyload.js'])
    .pipe(gulp.dest("dist/src"));
});
//移动且压缩src文件夹下的 除l10n文件夹以外的 .js文件
gulp.task('js',function(){
     return gulp.src(['src/**/**/*.js','!src/l10n/*.js'])
    .pipe($.uglify())   
    .pipe(gulp.dest("dist/src"));
});
// 压缩所有src 下面的js文件
// gulp.task('js',function(){
//      return gulp.src(['src/**/**/*.js','!src/l10n/*.js','!src/services/*.js','!src/directives/**/*.js','!src/controllers/**/*.js',])
//     // .pipe($.uglify())   
//     .pipe(gulp.dest("dist/src"));
// });
// main
// gulp.task('js1',function(){
//      return gulp.src(['src/main.js','src/config.router.js','src/app.js'])
//     .pipe($.uglify())    
//     .pipe(gulp.dest("dist/src"));
// });
// gulp.task('jsController',function(){
//      return gulp.src('src/controllers/**/*.js')
//     .pipe($.uglify())    
//     .pipe(gulp.dest("dist/src/controllers/"));
// });
// gulp.task('jsService',function(){
//      return gulp.src('src/services/*.js')
//     .pipe($.uglify())    
//     .pipe(gulp.dest("dist/src/services"));
// });
// gulp.task('jsDirectives',function(){
//      return gulp.src('src/directives/*.js')
//     .pipe($.uglify())    
//     .pipe(gulp.dest("dist/src/directives"));
// });

//生成index(压缩service、directive)
gulp.task('build:index',function () {
    var options = {
        removeComments: true,
        collapseWhitespace: true,
        collapseBooleanAttributes: true,
        removeEmptyAttributes: true,
        removeScriptTypeAttributes: true,
        removeStyleLinkTypeAttributes: true,
        minifyJS: true,
        minifyCSS: true  
    };
    return gulp.src(paths.index)
        .pipe($.useref())
        .pipe(htmlmin(options))
        .pipe(gulp.dest('dist'))
        .pipe($.plumber())
});

//?minJs.js 没有使用过
gulp.task("build:unjs",function(){
    return gulp.src(paths.scripts.service) 
            .pipe(concat('minJs.js'))
            // .pipe($.uglify())
            .pipe(gulp.dest('dist'))  
})
//end 没有使用过

gulp.task('replaceCtrl',function(){
    return gulp.src('dist/src/config.router.js')
        .pipe($.replace('.js',".js?v="+moment().format('YYMMDDHHmm')))
        .pipe($.replace('.html',".html?v="+moment().format('YYMMDDHHmm')))
        .pipe(gulp.dest('dist/src'));
})
gulp.task('renameTesthtml',function(){
    return gulp.src("dist/test.html")
        .pipe(rename("index.html"))
        .pipe(gulp.dest("dist"));
})
gulp.task('replaceIndex',function(){
    return gulp.src('dist/index.html')
        .pipe($.replace('dist/src/services', 'src/services'))
        .pipe($.replace('dist/src/directives', 'src/directives'))
        .pipe($.replace(/\.\.\/src\/.*?\.js/igm,function(str){
            console.log(str)
            return str + '?v=' + moment().format('YYMMDDHHmm')
        }))
        .pipe($.replace(/\.\.\/src\/.*?\.css/igm,function(str){
            return str + '?v=' + moment().format('YYMMDDHHmm')
        }))
        .pipe(gulp.dest('dist'));
})
gulp.task('bootstrapCss', function () {
    return gulp.src('src/css/bootstrap.css')
        .pipe(concat('bootstrap.min.css')) 
        .pipe($.minifyCss())
        .pipe(gulp.dest('dist/src/css'));
});
gulp.task('testCss', function () {
    return gulp.src(['src/css/*.css','!src/css/bootstrap.css'])
        .pipe(concat('app.min.css')) 
        .pipe($.minifyCss())
        .pipe(gulp.dest('dist/src/css'));
});

//复制文件
gulp.task('copy:ico',function(){
    return gulp.src("src/*.ico")
    .pipe(gulp.dest("dist"));
});
gulp.task('copy:tpl',function(){
      return  gulp.src("src/tpl/**/*")
        .pipe(gulp.dest("dist/src/tpl/"));
});
gulp.task('copy:content',function(){
     return   gulp.src("src/tpl/app.html")
        .pipe(gulp.dest("dist/src/tpl"));
});
gulp.task('copy:fonts',function(){
      return  gulp.src("src/fonts/*")
        .pipe(gulp.dest("dist/src/fonts"));
});
gulp.task('copy:img',function(){
     return   gulp.src("src/img/*")
        .pipe(imagemin())
        .pipe(gulp.dest("dist/src/img"));
});

gulp.task('copy:vendor',function(){
  return  gulp.src("vendor/**/*")
        .pipe($.if('*.js', $.uglify()))  
        .pipe(gulp.dest("dist/vendor"));
});
// ?main.min.js
gulp.task('build:residue',function(){
    return gulp.src(paths.scripts.residue)
            .pipe(concat('main.min.js'))
            .pipe($.uglify())
            .pipe(gulp.dest('dist/src'))  
})

gulp.task('copy',['copy:tpl','copy:ico','copy:content','copy:fonts','copy:img','copy:vendor']);

gulp.task('build', function(callback) {
  runSequence(
    "clean:dist",['bootstrapCss','testCss','copy','js'],
    ['build:residue'],
    ['build:index'],
    ['replaceCtrl'],
    ['renameTesthtml'],
    ['replaceIndex'],
    // ['build:component'],,'jsService','jsDirectives','jsController','js1'
    // ['rev:component'],
    callback)
});